package com.handydata.antifraud.ws.dap;

import java.util.Date;

import javax.annotation.PostConstruct;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.handydata.antifraud.annotation.Comment;
import com.handydata.antifraud.common.constant.DataSourceCode;
import com.handydata.antifraud.common.exception.WsInvokeException;
import com.handydata.antifraud.to.dap.DataDianHuaBangReqTO;
import com.handydata.antifraud.to.dap.DataDianHuaBangResTO;
import com.handydata.antifraud.util.DateUtil;
import com.handydata.antifraud.util.encrypt.Md5Utils;
import com.handydata.antifraud.ws.WsInvocationService;

/**
 * 电话帮黑名单
 */
@Slf4j
@Service("dataDianHuaBangWsService")
@Comment("电话帮黑名单")
public class DataDianHuaBangWsServiceImpl extends DataPlatformWsService<DataDianHuaBangReqTO, DataDianHuaBangResTO>
	implements WsInvocationService<DataDianHuaBangReqTO, DataDianHuaBangResTO> {

//	@Autowired
//	private DataCallLogsService dataCallLogsService;
	
	@Override
	public DataDianHuaBangResTO query(DataDianHuaBangReqTO req) throws WsInvokeException {
		log.info("电话帮黑名单请求参数 {}", req);
		DataDianHuaBangResTO resTO = new DataDianHuaBangResTO();
		if (StringUtils.isEmpty(req.getName())) {
			log.error("电话帮黑名单参数校验 {}", "name为空");
			resTO.setResCode("1111");
			resTO.setResMsg("电话帮黑名单接口name参数为空");
			return resTO;
		}
		if (StringUtils.isEmpty(req.getIdCard())) {
			log.error("电话帮黑名单参数校验 {}", "idCard为空");
			resTO.setResCode("1111");
			resTO.setResMsg("电话帮黑名单接口idCard参数为空");
			return resTO;
		}
		if (StringUtils.isEmpty(req.getPhoneNum())) {
			log.error("电话帮黑名单参数校验 {}", "phone为空");
			resTO.setResCode("1111");
			resTO.setResMsg("电话帮黑名单接口phone参数为空");
			return resTO;
		}
		this.dataType = DataSourceCode.DATA_DIAN_HUA_BANG.getCode();
		resTO = executeQuery(req);
		// 行内压测挡板处理
//		try {
//			Thread.sleep(250);
//		} catch (InterruptedException e) {
//			e.printStackTrace();
//		}
//		模拟数据源返回成功结果      success
//		 1
//		String data = "{\"resCode\":\"0000\",\"resMsg\":\"查询成功\",\"resData\":{\"is_black\":\"0\"}}";
//		 3
//		String data = "{\"resCode\":\"0002\",\"resMsg\":\"invalid parameter idnum\"}";
//		 4
//		String data = "{\"resCode\":\"0000\",\"resMsg\":\"查询成功\",\"resData\":{\"black_type\":[\"1\"],\"is_black\":\"1\"}}";
//		 5
//		String data = "{\"resCode\":\"0000\",\"resMsg\":\"查询成功\",\"resData\":{\"black_type\":[\"5\"],\"is_black\":\"1\"}}";
//		 6
//		String data = "{\"resCode\":\"0000\",\"resMsg\":\"查询成功\",\"resData\":{\"black_type\":[\"3\"],\"is_black\":\"1\"}}";
//		 7
//		String data = "{\"resCode\":\"0000\",\"resMsg\":\"查询成功\",\"resData\":{\"black_type\":[\"2\"],\"is_black\":\"1\"}}";
//		JSONObject jasonObject = JSONObject.parseObject(data);
//		if (null != jasonObject) {
//			if ("0000".equals(jasonObject.getString("resCode"))) {
//    			String overdueList = "0";
//    			String lostList = "0";
//    			String badList = "0";
//    			String fraudList = "0";
//    			JSONObject resData = jasonObject.getJSONObject("resData");
//    			String isBlack = resData.getString("is_black");
//    			if("1".equals(isBlack)) {
//    				JSONArray blackTypeArr = resData.getJSONArray("black_type");
//        			for(int i=0;i<blackTypeArr.size();i++) {
//        				String blackType =(String)blackTypeArr.get(i);
//        				if("1".equals(blackType)) {
//        					overdueList = "1";
//        				}
//        				if("2".equals(blackType)) {
//        					fraudList = "1";
//        				}
//        				if("3".equals(blackType)) {
//        					badList = "1";
//        				}
//        				if("5".equals(blackType)) {
//        					lostList = "1";
//        				}
//        			}
//    			}
//    			resTO.setCreditOverdueResult(overdueList);
//    			resTO.setCreditLossResult(lostList);
//    			resTO.setCreditFraudResult(fraudList);
//    			resTO.setBadListResult(badList);
//    		}
//			resTO.setResCode((String)jasonObject.get("resCode"));
//			resTO.setResMsg((String)jasonObject.get("resMsg"));
//			
//			// 挡板入库
//			DataCallLogsReqBO dataCallLogsReqBO = new DataCallLogsReqBO();
//			dataCallLogsReqBO.setId(UUID.randomUUID().toString().replace("-", ""));
//			dataCallLogsReqBO.setParams(JSONObject.toJSONString(req));
//			dataCallLogsReqBO.setElapsed(250);
//			dataCallLogsReqBO.setWselapsed(250);
//			dataCallLogsReqBO.setDataType(this.dataType);
//			dataCallLogsReqBO.setResCode("0000");
//			dataCallLogsReqBO.setResMsg("查询成功");
//			dataCallLogsReqBO.setResult(data);
//			dataCallLogsReqBO.setOrderId(req.getOrderId());
//			dataCallLogsReqBO.setUpdateTime(new Date());
//			dataCallLogsReqBO.setCreateTime(new Date());
//			dataCallLogsService.createDataCallLogs(dataCallLogsReqBO);
//		}	
		return resTO;
	}

	@Override
	protected String createQueryXml(DataDianHuaBangReqTO req) {
		StringBuilder xml = new StringBuilder();
		xml.append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>");
		xml.append("<subatm>");
		xml.append("<application>GwBiz.Req</application>");
		xml.append("<version>1.0.0</version>");
		xml.append("<sendTime>").append(DateUtil.now14()).append("</sendTime>");
		xml.append("<transCode>300664</transCode>");
		xml.append("<channelId>").append(encryInfo.getChannelId()).append("</channelId>");
		xml.append("<channelOrderId>").append(DateUtil.now17()).append("</channelOrderId>");
		xml.append("<name>").append(Md5Utils.md5ToHexStr(req.getName())).append("</name>");
		xml.append("<idnum>").append(Md5Utils.md5ToHexStr(req.getIdCard())).append("</idnum>");
		xml.append("<phone>").append(Md5Utils.md5ToHexStr(req.getPhoneNum())).append("</phone>");
//		xml.append("<name>").append(req.getName()).append("</name>");
//		xml.append("<idnum>").append(req.getIdCard()).append("</idnum>");
//		xml.append("<phone>").append(req.getPhoneNum()).append("</phone>");
		xml.append("<lng>").append(req.getLng()).append("</lng>");
		xml.append("<lat>").append(req.getLat()).append("</lat>");
		xml.append("<address>").append(req.getAddress()).append("</address>");
		xml.append("<queryMonth>").append(req.getQueryMonth()).append("</queryMonth>");
		xml.append("</subatm>");
		log.info("电话帮黑名单接口调用翰迪数平台请求报文：{}", xml);
		req.setQueryXml(xml.toString());
		return xml.toString();
	}

	@Override
	protected DataDianHuaBangResTO parseResultAndSave(String resultXml,	String orderId, Date createDate) {
		log.info("调用电话帮黑名单接口返回报文：{}", resultXml);
		DataDianHuaBangResTO resTO = new DataDianHuaBangResTO();
		try {
			// 解析xml，保存本地DB
			JSONObject jasonObject = JSONObject.parseObject(resultXml);
			if (null != jasonObject) {
				if ("0000".equals(jasonObject.getString("resCode"))) {
	    			String overdueList = "0";
	    			String lostList = "0";
	    			String badList = "0";
	    			String fraudList = "0";
	    			JSONObject resData = jasonObject.getJSONObject("resData");
	    			String isBlack = resData.getString("is_black");
	    			if("1".equals(isBlack)) {
	    				JSONArray blackTypeArr = resData.getJSONArray("black_type");
						for (Object obj : blackTypeArr) {
							String blackType = (String) obj;
							if ("1".equals(blackType)) {
								overdueList = "1";
							}
							if ("2".equals(blackType)) {
								fraudList = "1";
							}
							if ("3".equals(blackType)) {
								badList = "1";
							}
							if ("5".equals(blackType)) {
								lostList = "1";
							}
						}
	    			}
	    			resTO.setCreditOverdueResult(overdueList);
	    			resTO.setCreditLossResult(lostList);
	    			resTO.setCreditFraudResult(fraudList);
	    			resTO.setBadListResult(badList);
	    		}
				resTO.setResCode((String)jasonObject.get("resCode"));
				resTO.setResMsg((String)jasonObject.get("resMsg"));
				//resTO.setReqId(dataCallLogsReqBO.getId());
			} else {
				resTO.setResCode("1111");
				resTO.setResMsg("电话帮黑名单返回数据异常");
			}
		} catch (Exception e) {
			log.info("调用电话帮黑名单接口异常：{}", e.getMessage());
			resTO.setResCode("1111");
			resTO.setResMsg("调用电话帮黑名单接口异常");
		}
		log.info("调用电话帮黑名单接口返回结果：{}", JSONObject.toJSONString(resTO));
		return resTO;
	}

	@SuppressWarnings("unchecked")
	@PostConstruct
	@Override
	public void register() {
		registerToWsServiceFactory(this, DataDianHuaBangReqTO.class);
	}
    
}
